<?php
/*
 * Created on Sep 8, 2012
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

include_once("utils/CouponUtils.php");

include_once("domain/LinkDomain.php");
include_once("domain/MerchantDomain.php");
include_once("domain/AdvertiserDomain.php");
include_once("domain/CouponImageDomain.php");

include_once("impl/CouponImpl.php");
include_once("impl/MerchantImpl.php");
include_once("impl/AdvertiserImpl.php");


class FeedImpl
{
	private $DBTag;
	private $couponImpl;
	private $merImpl;
	private $adImpl;
	private $catImpl;
	
	private $ga;
	
	private $isAddNewMer;
	
	function FeedImpl($DBTag)
	{
		$this->DBTag 		= $DBTag;
		
		$this->couponImpl 	= new CouponImpl($DBTag);
		$this->merImpl 		= new MerchantImpl($DBTag);
		$this->adImpl 		= new AdvertiserImpl($DBTag);
		$this->catImpl 		= new CategoryImpl($DBTag);
		
		$this->ga 			= new GoogleAffiliateApi();
		$this->ga->init();
	}
	
	
	public function addCoupon($link)
	{
		$oMer 		= $this->merImpl->getMerchantByAdvertiserId($link->getAdvertiserId());
		
		$id			= 0;
		$oCat 		= false;
		$advertiser	= false;
		$this->isAddNewMer = false;
		
		// find merchant by alias
		if(!is_object($oMer)){
			$adv = $this->ga->getAdvertiser($link->getAdvertiserId());
				
			if(is_object($adv)){
				$oMer = $this->merImpl->getByAlias($adv->getName());
			}
		}
		
		if(is_object($oMer)){					
			$adverCatName 	= $this->merImpl->getAdvertiserCategory(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());
			
			if(empty($adverCatName)){
				if(!is_object($adv))
					$adv = $this->ga->getAdvertiser($link->getAdvertiserId());
				
				if(is_object($adv)){		
					$this->adImpl->updateMerchantByGooglAdvertiser($oMer, $adv);
				}
			}
			
			$adverCatName 	= $this->merImpl->getAdvertiserCategory(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());
		}else{
			if(!is_object($adv)){
				$adv = $this->ga->getAdvertiser($link->getAdvertiserId());
			}
			
			echo "merchant is empty.";
			echo "\n";
			
			if(is_object($adv)){
				echo "need add new merchant, linkId : " . $link->getId();
				echo "\n";
				echo "need add new merchant, AdvertiserId : " . $link->getAdvertiserId();
				echo "\n";
				
				$oMer = $this->adImpl->addMerchantByGooglAdvertiser($adv);
				
				if(is_object($oMer)){
					$this->isAddNewMer = true;
					$this->getNewMerchantInfo($link, $adv, $oMer);

					$adverCatName 	= $this->merImpl->getAdvertiserCategory(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());
				}
			}

		}
		

		
		if(!empty($adverCatName))
			$oCat = $this->catImpl->getCategoryByAlias($adverCatName);
		
		if(!is_object($oCat)){
			echo "category id requested.";
			echo "\n";
			
			echo "AdvertiserId : " . $link->getAdvertiserId();
			echo "\n";
			
			echo "adverCatName : $adverCatName";
			echo "\n";
			
			if(is_object($oMer)){
				echo "merchant id : " . $oMer->getId();
				echo "\n";
			}else{
				echo "merchant miss";
				echo "\n";
			}
			
			return -1;
		}
		
		
		if(is_object($oMer)){
			$code	= '';
			$name	= $link->getName();
			
			// filter name
			if ($link->getPromotionType() == 'coupon'){
				$startFlag 	= 'with coupon code ';
				$endFlag	= '. expirat';
				
				$code 	= StringUtils::getCutValue($startFlag, $endFlag, $name);
				$name 	= StringUtils::getStartValue(' with coupon code', $name);
			}
		
			//convert creative type
			$creativeType 	= 0;
			$width			= 0;
			$height			= 0;
			
			// parse code from coupon name
			if(empty($code)){
				$code = CouponUtils::findCode($name);
			}
			
			// filter link name
			$pattern[0] = "/(\d+)x(\d+)/i";
			$pattern[1] = "/(\d+) x (\d+)/i";

			$replacement 	= '';
			$filtername 	= preg_replace($pattern[0], $replacement, $name);
			$filtername 	= preg_replace($pattern[1], $replacement, $filtername);
			$filtername 	= str_ireplace ('banner', $replacement, $filtername);
//			$filtername 	= str_ireplace (' logo', $replacement, $filtername);
//			$filtername 	= str_ireplace (' Logo', $replacement, $filtername);
			
			$filtername 	= trim($filtername, ' ');
			$filtername 	= trim($filtername, '-');
			$filtername 	= trim($filtername, '_');
			$filtername 	= trim($filtername, ' ');
			
			$description 	= $link->getDescription();
			
			if($description == $link->getName())
				$description = '';
			
			$cd = new CouponDomain();
			
			if($link->getLinkType() == 'BANNER'){
				$creativeType = '1';
				
				$imgInfo = $this->getImageInfo($link->getImpressionTrackingUrl());
				
				$width	= $imgInfo['width'];
				$height	= $imgInfo['height'];
				
				if($imgInfo['isValid']){
								
				$couponImg = new CouponImageDomain();
				
				$couponImg->setName($filtername);
				$couponImg->setWidth($width);
				$couponImg->setHeight($height);				
				$couponImg->setImpressionTrackingUrl($link->getImpressionTrackingUrl());
				$couponImg->setImageAltText($link->getImageAltText());
				$couponImg->setUseType('0');
				$couponImg->setStatus('1');
				
				$cd->setCouponImage($couponImg);
					
				}else{
					$creativeType = '2';// image size too small , convert type to text
				}
			}else if ($link->getLinkType() == 'TEXT'){
				$creativeType = '2';
			}else
				return -1;		
			
			$cd->setName($filtername);
			$cd->setDescript($description);
			$cd->setStartDate($link->getStartDate());
			$cd->setEndDate($link->getEndDate());
			
			$cd->setCreativeType($creativeType);
			$cd->setMerchantId($oMer->getId());
		
			$cd->setCode($code);
			$cd->setCostType(1);
			
			$cd->setTrackingURL($link->getClickTrackingUrl());
			
			$cd->setSourceId(GlobalConstant::SOURCE_ID_GOOGLE);
			$cd->setStatus(1);			
			
			
			$id = $this->couponImpl->add($cd);
			
			
			
			if($cd->getId() > 0){
//				echo "\n";
//				echo "coupon id: " . $cd->getId();
//				echo "\n";
//				
				
				// add category of coupon
				if(is_object($oCat)){
					$this->couponImpl->addCategory($cd->getId(), $oCat->getId());
				}
				
				// add attributes
				$attributeIdForPromoType = $this->getAttributeIdForPromoType($link->getPromotionType(), $link->getName());
				
				if($attributeIdForPromoType > 0){
					$this->couponImpl->addAttribute($cd->getId(), $attributeIdForPromoType, 'Promo Type');
				}
			}
		}else{
			echo "merchant miss.";
			echo "\n";
			
			echo "AdvertiserId : " . $link->getAdvertiserId();
			echo "\n";
			
			return -1;
		}
		
		return $id;
	}
	
	
	private function getAttributeIdForPromoType($promoTypeName, $couponName)
	{
		$attribteId = 0;
		
		switch ($promoTypeName) {
		    case "Ongoing Promotion":
		        $attribteId = 31; 
		        break;
		    case "Sale":
		       $attribteId = 32; 
		        break;
		    case "Coupon":
		        $attribteId = 33; 
		        break;
		    case "Unspecified":
		        $attribteId = 34; 
		        break;
		    case "Price Cut":
		        $attribteId = 35; 
		        break;
		    case "Product Promotion":
		        $attribteId = 36; 
		        break;
		    case "Free Shipping":
		        $attribteId = 2; 
		        break;
		    case "Percent Off":
		        $attribteId = 1; 
		        break;
		    case "Free Gift":
		        $attribteId = 37; 
		        break;
		    case "Sweepstakes":
		        $attribteId = 38; 
		        break;
		    case "Free Gift Wrap":
		        $attribteId = 39; 
		        break;
		    case "Buy x Get y":
		        $attribteId = 40; 
		        break;
	
		}
		
		if($attribteId == 34){// Unspecified
			$pos1 = strrpos($couponName, '$');
			$pos2 = strrpos($couponName, '%');
			if($pos1 > 0 || $pos2 > 0 || $pos1 === 0 || $pos2 === 0){
				
			}else
				$attribteId = 0;
		}
		
		return $attribteId;
	}
	
	private function getImageInfo($filename)
	{
		$arrinfo 	= array();		
		$imageinfo 	= @getImageSize ($filename);
		
//		$arrinfo['isValid'] = 0;
//		$arrinfo['width'] 	= $imageinfo[0];
//		$arrinfo['height']	= $imageinfo[1];
//		$arrinfo['type']	= $imageinfo[2];		
//		
//		if($arrinfo['width'] > 20 || $arrinfo['height'] > 20){
//			$arrinfo['isValid'] = 1;
//		}
		
		$arrinfo['isValid'] = 1;
		$arrinfo['width'] 	= 0;
		$arrinfo['height']	= 0;
		
		return $arrinfo;
	}
	
	public function isAddNewMerchant()
	{
		return $this->isAddNewMer;
	}
	
	
	public function getNewMerchantInfo($link, $adv, $mer)
	{
		$arrinfo = array();
		
		$arrinfo['advertiserId'] 	= $link->getAdvertiserId();
		$arrinfo['advertiserName'] 	= $adv->getName();
		$arrinfo['merchantId'] 		= $mer->getId();
		
		return $arrinfo;
	}
}
?>
